package com.changgou.order.service.impl;

import com.changgou.goods.feign.SkuFeign;
import com.changgou.goods.feign.SpuFeign;
import com.changgou.goods.pojo.Sku;
import com.changgou.goods.pojo.Spu;
import com.changgou.order.pojo.OrderItem;
import com.changgou.order.service.CartService;
import entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;


/**订单购物车业务实现类
 * @author zhengjd
 * @date 2020/5/17 22:58
 */
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private SkuFeign skuFeign;

    @Autowired
    private SpuFeign spuFeign;

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 添加购物车
     * @param num  添加商品数量
     * @param id  skuId
     * @param username  用户名
     */
    @Override
    public void add(Integer num, Long id, String username) {

        if (num<=0){
            //如果num小于等于0，则删除Redis中的商品数据
            redisTemplate.boundHashOps("Cart_"+username).delete(id);
            return;
        }
        //调用feign获取sku商品数据
        Result<Sku> skuResult = skuFeign.findById(id);
        Sku sku = skuResult.getData();
        //根据spuId获取spu数据
        Result<Spu> spuResult = spuFeign.findById(sku.getSpuId());
        Spu spu = spuResult.getData();
        //将数据设置到orderItem中
        OrderItem orderItem = new OrderItem();
        orderItem.setCategoryId1(spu.getCategory1Id());
        orderItem.setCategoryId2(spu.getCategory2Id());
        orderItem.setCategoryId3(spu.getCategory3Id());
        orderItem.setImage(sku.getImage());
        orderItem.setMoney(sku.getPrice()* num);
        orderItem.setName(sku.getName());
        orderItem.setNum(num);
        orderItem.setPrice(sku.getPrice());
        orderItem.setPayMoney(sku.getPrice()*num);
        orderItem.setSkuId(id);
        orderItem.setSpuId(spu.getId());
        //将orderItem数据添加到Redis中（hash类型）
        redisTemplate.boundHashOps("Cart_"+username).put(id,orderItem);
    }

    /**
     * 查询购物车列表
     * @return
     */
    @Override
    public List<OrderItem> list(String username) {

        List<OrderItem> list = redisTemplate.boundHashOps("Cart_" + username).values();
        return list;
    }
}
